import 'dart:io';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import 'package:xcite/core/widgets/loading_widget.dart';

import '../../core/models/user_model.dart';
import '../../core/providers/user_provider.dart';
import '../../core/utils/toast_helper.dart';

class ProfileModificationScreen extends ConsumerStatefulWidget {
  const ProfileModificationScreen({super.key});

  @override
  ConsumerState<ProfileModificationScreen> createState() =>
      _ProfileModificationScreenState();
}

class _ProfileModificationScreenState
    extends ConsumerState<ProfileModificationScreen> {
  late TextEditingController _usernameController;
  late TextEditingController _descriptionController;
  String? _selectedAvatarPath;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    final currentUser = ref.read(currentUserProvider);
    _usernameController = TextEditingController(
      text: currentUser?.username ?? '',
    );
    _descriptionController = TextEditingController(
      text: currentUser?.description ?? '',
    );
    _selectedAvatarPath = currentUser?.avatar;
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final currentUser = ref.watch(currentUserProvider);

    if (currentUser == null) {
      return Scaffold(
        body: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/resources/common_bg_2.png'),
              fit: BoxFit.cover,
            ),
          ),
          child: SafeArea(
            child:
                [
                  Text(
                    'Please login first',
                    style: TextStyle(
                      fontSize: 18.sp,
                      color: Colors.white,
                      fontWeight: FontWeight.w600,
                    ),
                  ).center(),
                ].toColumn(),
          ),
        ),
      );
    }

    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/common_bg_2.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child:
              [
                _buildHeaderSection(),

                Expanded(
                  child: SingleChildScrollView(
                    padding: EdgeInsets.symmetric(horizontal: 16.w),
                    child:
                        [
                          SizedBox(height: 40.h),

                          _buildAvatarSection(currentUser),
                          SizedBox(height: 40.h),

                          _buildUsernameInputField(),
                          SizedBox(height: 20.h),

                          _buildDescriptionInputField(),
                          SizedBox(height: 60.h),

                          _buildConfirmButton(),
                          SizedBox(height: 40.h),
                        ].toColumn(),
                  ),
                ),
              ].toColumn(),
        ),
      ),
    );
  }

  Widget _buildHeaderSection() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
      child:
          [
            Container(
              width: 30.w,
              height: 30.w,
              decoration: BoxDecoration(
                color: Colors.black,
                shape: BoxShape.circle,
              ),
              child:
                  Icon(Icons.arrow_back_ios)
                      .iconSize(18.sp)
                      .iconColor(Colors.white)
                      .inkWell(onTap: () => GoRouter.of(context).pop())
                      .center(),
            ),

            Spacer(),

            Text(
              'Edit Profile',
              style: TextStyle(
                fontSize: 24.sp,
                color: Colors.black,
                fontWeight: FontWeight.bold,
                fontFamily: 'PoetsenOne',
              ),
            ),

            Spacer(),

            SizedBox(width: 24.w),
          ].toRow(),
    );
  }

  Widget _buildAvatarSection(UserDataEntity currentUser) {
    return [
      Container(
        width: 120.w,
        height: 120.w,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          border: Border.all(color: Colors.black, width: 2.w),
          image: DecorationImage(
            image:
                _selectedAvatarPath != null
                    ? (_selectedAvatarPath!.startsWith('assets/')
                        ? AssetImage(_selectedAvatarPath!) as ImageProvider
                        : FileImage(File(_selectedAvatarPath!)))
                    : AssetImage(currentUser.avatar),
            fit: BoxFit.cover,
          ),
        ),
      ).inkWell(onTap: _handleAvatarSelection),

      SizedBox(height: 12.h),

      Text(
        'Tap to change avatar',
        style: TextStyle(
          fontSize: 14.sp,
          color: Colors.white.withValues(alpha: 0.8),
        ),
      ),
    ].toColumn().center();
  }

  Widget _buildUsernameInputField() {
    return Container(
      padding: EdgeInsets.only(right: 2.w, bottom: 2.w),
      decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Container(
        height: 56.h,
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(color: Colors.black),
        ),
        child: Center(
          child: TextField(
            controller: _usernameController,
            style: TextStyle(fontSize: 16.sp, color: Colors.black87),
            decoration: InputDecoration(
              border: InputBorder.none,
              hintText: 'Enter username',
              hintStyle: TextStyle(
                fontSize: 16.sp,
                color: Colors.grey.shade500,
              ),
              contentPadding: EdgeInsets.zero,
              isDense: true,
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildDescriptionInputField() {
    return Container(
      padding: EdgeInsets.only(right: 2.w, bottom: 2.w),
      decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Container(
        height: 56.h,
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(color: Colors.black),
        ),
        child: Center(
          child: TextField(
            controller: _descriptionController,
            style: TextStyle(fontSize: 16.sp, color: Colors.black87),
            decoration: InputDecoration(
              border: InputBorder.none,
              hintText: 'Enter description',
              hintStyle: TextStyle(
                fontSize: 16.sp,
                color: Colors.grey.shade500,
              ),
              contentPadding: EdgeInsets.zero,
              isDense: true,
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildConfirmButton() {
    return Stack(
      children: [
        Image.asset(
          'assets/resources/confirm_button_long.png',
          width: double.infinity,
          height: 56.h,
          fit: BoxFit.fill,
        ),

        if (_isLoading)
          SizedBox(
            width: double.infinity,
            height: 56.h,
            child:
                CircularProgressIndicator(
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                ).center(),
          ),
      ],
    ).inkWell(onTap: _isLoading ? null : _handleConfirmChanges);
  }

  void _handleAvatarSelection() async {
    try {
      final List<AssetEntity>? result = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.image,
          themeColor: Color(0xFF2AB061),
          textDelegate: AssetPickerTextDelegate(),
        ),
      );

      if (result != null && result.isNotEmpty) {
        final AssetEntity asset = result.first;
        final File? file = await asset.file;

        if (file != null) {
          final Directory appDocDir = await getApplicationDocumentsDirectory();
          final String avatarsDir = path.join(appDocDir.path, 'avatars');

          final Directory avatarDirectory = Directory(avatarsDir);
          if (!await avatarDirectory.exists()) {
            await avatarDirectory.create(recursive: true);
          }

          final String fileName =
              'avatar_${DateTime.now().millisecondsSinceEpoch}.jpg';
          final String newPath = path.join(avatarsDir, fileName);

          final File newFile = await file.copy(newPath);

          setState(() {
            _selectedAvatarPath = newFile.path;
          });

          if (mounted) {
            ToastHelper.success(
              'Avatar selected successfully',
              context: context,
            );
          }
        }
      }
    } catch (e) {
      if (mounted) {
        ToastHelper.error('Failed to select avatar', context: context);
      }
    }
  }

  void _handleConfirmChanges() async {
    final currentUser = ref.read(currentUserProvider);
    if (currentUser == null) return;

    final username = _usernameController.text.trim();
    final description = _descriptionController.text.trim();

    if (username.isEmpty) {
      ToastHelper.warning('Username cannot be empty', context: context);
      return;
    }

    if (username.length < 2) {
      ToastHelper.warning(
        'Username must be at least 2 characters',
        context: context,
      );
      return;
    }

    if (description.length > 200) {
      ToastHelper.warning(
        'Description cannot exceed 200 characters',
        context: context,
      );
      return;
    }

    setState(() {
      _isLoading = true;
    });

    LoadingWidget.showFullScreen(context);

    try {
      final userNotifier = ref.read(userProvider.notifier);

      final success = await userNotifier.updateUserInfo(
        username: username,
        description: description,
        avatar: _selectedAvatarPath ?? currentUser.avatar,
      );

      if (mounted) {
        setState(() {
          _isLoading = false;
        });

        if (success) {
          ToastHelper.success('Profile updated successfully', context: context);
          LoadingWidget.hide(context);
          await Future.delayed(Duration(milliseconds: 1500));

          if (mounted) {
            GoRouter.of(context).pop();
          }
        } else {
          ToastHelper.error('Failed to update profile', context: context);
        }
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
        ToastHelper.error('An error occurred', context: context);
      }
    }
  }
}
